package lsdm.jmeter;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.*;

public class JsonUtil {
    static String dir = "src/main/data/";

    public static void main(String[] args) {
        System.out.println(JSONObject.quote("123123"));
        readJsonFile(dir + "data.json");
    }

    public static void readJsonFile(String path) {
        File file = new File(path);
        try {
//            读取JSON文件
            FileReader fileReader = new FileReader(file);
            int ch = 0;
//            存放读取后的数据
            StringBuffer sb = new StringBuffer();
            while ((ch = fileReader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            String rs = sb.toString();
//            json文件处理
            jsonDataHander(rs);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param str 带处理的JSON字符串
     */
    public static void jsonDataHander(String str) {
//        将字符串转JSON对象
        JSONObject jsonObj = new JSONObject(str);
//        System.out.println(jsonObj);
//        获取data数组
        JSONArray data = jsonObj.getJSONArray("data");
//        System.out.println(data);
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(dir + "user.txt");
        } catch (IOException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < data.length(); i++) {
            JSONObject user = data.getJSONObject(i);
            String userName = user.getString("loginName");
            String realName = user.getString("userName");
            try {
                fileWriter.append(userName + "," + "123," + realName +"\r\n");
//                fileWriter.write(userName + "," + "123," + realName +"\r\n");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
